package com.test.zhangxin.mycamera;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String APP_PACKAGE_NAME = "cn.poco.interphoto2";
    private static final String APP_POCOCAMERA = "cn.poco.interphoto2.PocoCamera";
    private Button mShotBtn;
    private ImageView mImg;
    private MainActivity mContext;
    private Button mVedioBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mShotBtn = (Button) findViewById(R.id.shot_btn);
        mVedioBtn = (Button) findViewById(R.id.vedio_btn);
        mImg = (ImageView) findViewById(R.id.img);
        mContext = MainActivity.this;
        mShotBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isAppInstaled(mContext, APP_PACKAGE_NAME) && getVersionCode(mContext) >= 12) {
                    //直接打开
                    //
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    ComponentName component = new ComponentName(APP_PACKAGE_NAME, APP_POCOCAMERA);
                    intent.setComponent(component);
                    startActivityForResult(intent, 1);
                } else {
                    //到商城中下载
                    Toast.makeText(mContext, "没有这个软件", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mVedioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isAppInstaled(mContext, APP_PACKAGE_NAME) && getVersionCode(mContext) >= 12) {
                    Intent intent = new Intent();
                    //激活系统的照相机进行录像
                    intent.setAction("android.media.action.VIDEO_CAPTURE");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    ComponentName component = new ComponentName(APP_PACKAGE_NAME, APP_POCOCAMERA);
                    intent.setComponent(component);
                    startActivityForResult(intent, 2);
                } else {
                    //到商城中下载
                    Toast.makeText(mContext, "没有这个软件", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    public boolean isAppInstaled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 获取软件版本号
     *
     * @param context 上下文
     * @return versionCode
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下的versionCode
            versionCode = context.getPackageManager().
                    getPackageInfo(APP_PACKAGE_NAME, 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, "请确认SD卡插入", Toast.LENGTH_SHORT).show();
            }
            if (requestCode == 1) {
                Bitmap bitmap = null;
                if (data != null) {
                    bitmap = (Bitmap) data.getExtras().get("data");
                }
                mImg.setImageBitmap(bitmap);
                saveImage(mContext, bitmap);
            } else if (requestCode == 2) {
                Log.e("zx", "---------" + data);
                //dat=file:///storage/emulated/0/beautyCamera/video/1499053010255.mp4
                Uri uri = data.getData();
                //拿到文件名,判断是路径还是id
                String string = uri.toString();
                int index = string.lastIndexOf("/");
                String fileName = string.substring(index + 1, string.length());
                if (fileName.contains(".")) {//路径
                    saveVedio(data, "video/" + fileName.split("\\.")[1]);
                } else {//id
                    String mineType = getMineIndexFromURI(uri);
                    saveVedio(data, mineType);
                }
            }
        }
    }

    /**
     * 根据Uri查找到媒体库的mineType
     *
     * @param contentUri
     * @return
     */
    public String getMineIndexFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Video.Media.MIME_TYPE};
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int mime_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
        cursor.moveToFirst();
        Log.d("mimetype", cursor.getString(mime_index));
        return cursor.getString(mime_index);
    }

    /**
     * 保存录像
     *
     * @param data
     * @param mineType
     */
    private void saveVedio(Intent data, String mineType) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
            fis = videoAsset.createInputStream();
            String path = Environment.getExternalStorageDirectory() + "/zxVideo";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File tmpFile = new File(path, SystemClock.currentThreadTimeMillis() + "." + mineType.split("/")[1]);
            fos = new FileOutputStream(tmpFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = fis.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
        } catch (IOException io_e) {
            io_e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 保存图片
     *
     * @param context
     * @param bmp
     */
    public static void saveImage(Context context, Bitmap bmp) {
        // 保存图片
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zxphoto";
        File appDir = new File(path);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "jpg");
        values.put(MediaStore.Images.ImageColumns.DATA, path);

        context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
        // 把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }
}